package com.springboot.frame.comm.domain;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import static com.springboot.frame.comm.util.CodeUtils.camelToUnderline;

/**
 * @author madman
 */
@Data
public final class Table {

  private Column keyColumn;

  private Class<?> superClass;

  private String jdbcName;

  private String comment;

  private String javaName;

  private Set<String> importPackages = new HashSet<>();

  private String baseColumnList;

  private Boolean isTableAnnotation = false;

  private List<Column> columns;

  private Map<String, FileTemplate> fileTemplates;

  public void setSuperClass(Class<?> superClass) {
    this.superClass = superClass;
    if (superClass != null) {
      this.importPackages.add(superClass.getName());
    }
  }

  public void setIsTableAnnotation(Boolean isTableAnnotation) {
    this.isTableAnnotation = isTableAnnotation;
    if (isTableAnnotation) {
      this.importPackages.add(isTableAnnotation ? "javax.persistence.Table" : null);
    }
  }

  public void setColumns(List<Column> columns) {
    this.columns = columns;
    StringBuilder names = new StringBuilder();
    int size = columns.size();
    for (int i = 0; i < size; i++) {
      Column column = columns.get(i);
      if (i == size - 1) {
        names.append(cov2col(column));
      } else {
        names.append(cov2col(column)).append(", ");
      }
    }
    this.baseColumnList = names.toString();
  }

  private String cov2col(Column column) {
    return column.getIsColumnAnnotation() ? column.getJdbcName() + " AS " + column.getProperty()
        : column.getJdbcName();
  }

  public List<String> getSuperColumns() {
    List<String> results = new ArrayList<>();
    if (superClass != null) {
      for (Field field : superClass.getDeclaredFields()) {
        String name = field.getName();
        try {
          if (field.isAnnotationPresent(javax.persistence.Column.class)) {
            String columnName = field.getAnnotation(javax.persistence.Column.class).name();
            if (StringUtils.isNotBlank(columnName)) {
              name = columnName;
            }
          }
        } catch (Exception e) {
          //to do nothing
        }
        results.add(camelToUnderline(name));
      }
    }
    return results;
  }

}
